package cn.icanci.ladybird.controller;

import cn.icanci.ladybird.common.util.RandomValueUtils;
import cn.icanci.ladybird.service.util.SendSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author: icanci
 * @date: Created in 2020/10/3 21:54
 * @classAction: 发送短信业务
 */
@RestController
@CrossOrigin
@RequestMapping("/api/v1/pub/common")
public class SendSmsController {
    @Autowired
    private SendSmsService sendSmsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/send/{phone}")
    public String getSmsCode(@PathVariable("phone") String phone) {
        // 调用方法发送 （模拟真实业务）
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            // 已经存在，没有过期
            return phone + " : " + code;
        }
        // 生成6位数验证码并且存储到Redis中
        code = String.valueOf(RandomValueUtils.getNum(100000, 999999));
        System.out.println(code);
        HashMap<String, Object> codeMap = new HashMap<>();
        codeMap.put("code", code);
        boolean isSend = sendSmsService.send(phone, "SMS_196653273", codeMap);
        if (isSend) {
            // 将手机号作为key,验证码作为 code，有效时间是5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return phone + " : " + code + " 发送成功";
        } else {
            return "发送失败";
        }
    }
}
